<?php
/**
 * CDN上报片源媒体注入进度处理类
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/3/12 11:50
 */

set_time_limit(0);error_reporting(0);
//header('Content-Type:text/xml; charset=utf-8');
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
$arr_dir = explode('|',str_replace(array('/','\\'), '|', __DIR__));
$str_dir = array_pop($arr_dir);
define('ORG_ID', $str_dir);
\ns_core\m_load::load("ns_core.m_config");
//加载 xml转为数组的np库
\ns_core\m_load::load_np("np_xml_to_array.class.php");
\ns_core\m_load::load_np("np_xml2array.class.php");
class notify
{
    //数据库/缓存处理类
    private $obj_dc = null;
    //SP ID
    private $str_sp_id = 'nmgd';
    //CDN上报XML
    private $str_xml_content = '';

    /**
     * 默认构造函数
     */
    public function __construct($str_xml)
    {
        $this->obj_dc = m_config::get_dc();
        $this->str_xml_content = $str_xml;
    }

    /**
     * 处理CDN上报信息入口
     */
    public function init()
    {
        $bool_ret = false;
        //处理CDN反馈的信息
        $str_content = m_config::trim_xml_header($this->str_xml_content);
        if(m_config::is_xml($str_content))
        {
            $dom = new DOMDocument('1.0', 'utf-8');
            $dom->loadXML($str_content);
            $xml = $dom->saveXML();
            //转化XML为数组格式
            $xml_arr = np_xml2array::getArrayData($xml);

            if(is_array($xml_arr) && !empty($xml_arr) && !empty($xml_arr['data']))
            {
                m_config::write_cdn_notify_log('[' . date('Y-m-d H:i:s') . ']'  . '接收数码CDN反馈，并开始处理', ORG_ID, '');
                //处理CDN上报信息核心函数
                $bool_ret = $this->_handler_feedback_content($xml_arr['data']);
            }
        }

        return $bool_ret;
    }

    /**
     * 处理CDN上报信息核心函数
     * @param $arr_content
     * @return bool true成功；false失败
     */
    private function _handler_feedback_content($arr_content)
    {
        //验证参数有效性
        $str_asset_id = isset($arr_content['attributes']['assetID']) ? $arr_content['attributes']['assetID'] : '';
        $str_provider_id = isset($arr_content['attributes']['providerID']) ? $arr_content['attributes']['providerID'] : '';
        $str_content_type= isset($arr_content['attributes']['contentType']) ? $arr_content['attributes']['contentType'] : 'vod';
        $str_volume_name = isset($arr_content['attributes']['volumeName']) ? $arr_content['attributes']['volumeName'] : '';
        if(empty($str_asset_id) || empty($str_provider_id) || empty($str_volume_name))
        {
            return false;
        }
        //根据媒资ID 查询SP信息
        $str_sql  = "select s.*,m.nns_cp_id ";
        $str_sql .= "from nns_mgtvbk_sp s LEFT JOIN nns_vod_media m ON LOCATE(CONCAT(',', m.`nns_cp_id`, ','),s.`nns_bind_cp`) > 0 ";
        $str_sql .= "where s.nns_state = 0 and m.nns_import_id = '{$str_asset_id}'";
        $arr_sp_info = nl_db_get_one($str_sql,$this->obj_dc->db());

        if(!is_array($arr_sp_info) || empty($arr_sp_info) || empty($arr_sp_info['nns_config']))
        {
            m_config::write_cdn_notify_log('根据片源媒资ID查询 SP信息失败。SQL：' .addslashes($str_sql), ORG_ID, '');
            return false;
        }
        //获取CDN播放串公共域名地址
        $str_sp_config = json_decode($arr_sp_info['nns_config']);
        $str_play_url_ip = is_object($str_sp_config) ? $str_sp_config->c2_play_url_ip : $str_sp_config['c2_play_url_ip'];
        unset($str_sp_config); unset($arr_sp_info);

        //子节点
        if(is_array($arr_content['children']) && !empty($arr_content['children']))
        {
            $bool_modify_ret = true; $str_play_url = ''; $str_modify_sql = '';

            $delivery = \ns_core\m_load::load_cdn_delivery_object(__FILE__);
            foreach($arr_content['children'] as $children)
            {
                //上报状态
                $str_bit_rate = isset($children['attributes']['subID']) ? $children['attributes']['subID'] : '';
                $state = isset($children['attributes']['state']) ? strtolower($children['attributes']['state']) : '';
                $percent_complete = isset($children['attributes']['percentComplete']) && strlen($children['attributes']['percentComplete']) > 0 ? $children['attributes']['percentComplete'] .'%' : '0%';
                $reason_code = isset($children['attributes']['reasonCode']) && strlen($children['attributes']['reasonCode']) > 0 ? $children['attributes']['reasonCode'] : '';
                if ($reason_code == '200')
                {
                    switch ($state)
                    {
                        case 'complete' :
                            $code = 0;
                            $reason = '注入CDN成功';
                            break;
                        case 'transfer' :
                            $code = 5;
                            $reason = '完成' . $percent_complete;
                            break;
                        case 'pending' :
                            $code = 1;
                            $reason = '';
                            break;
                        case 'canceled' :
                            $code = -1;
                            $reason = '注入失败';
                            break;
                        case 'ingest failure' :
                            $code = -1;
                            $reason = '注入失败';
                            break;
                        default:
                            $code = -1;
                            $reason = '注入失败';
                            break;
                    }
                }
                else if ($reason_code == '409')
                {
                    $code = 0;
                    $reason = 'CDN资源已经存在，注入成功';
                }
                else
                {
                    $code = -1;
                    $reason = '注入失败,原因:' . $state . '状态码:' . $reason_code;
                }

                //更新片源媒资的播放串地址
                $arr_media = array(
                    'media_where' => array(
                        'nns_import_id' => $str_asset_id,
                        'nns_kbps' => $str_bit_rate,
                    )
                );
                if($code === 0)
                {
                    $str_play_url = json_encode(array(
                        'play_url' => $str_play_url_ip . '/' . strtolower($str_content_type) . '/' . $str_provider_id . '_' . $str_asset_id . '_' . $str_bit_rate . '.m3u8',
                    ));

                    $arr_media['media_filed'] = array(
                            'nns_ext_url' => addslashes($str_play_url),
                    );

                    m_config::write_cdn_notify_log('片源【' . $str_asset_id . '】媒体内容注入CDN成功，更新播放串地址' . ($bool_modify_ret ? '成功' : '失败') . '。SQL：' . addslashes($str_modify_sql), ORG_ID, '');
                }
                else
                {
                    m_config::write_cdn_notify_log('片源【' . $str_asset_id . '】媒体内容注入CDN失败或正在注入', ORG_ID, '');
                }

                m_config::write_cdn_notify_log('开始进行反馈给上游', ORG_ID, '');
                $re_callback = $delivery->notify($arr_media, $code, $reason);
                m_config::write_cdn_notify_log('反馈结果为' . var_export($re_callback, true), ORG_ID, '');
                $str_play_url = '';
            }
            unset($bool_state); unset($str_play_url); unset($str_modify_sql);
        }
        return true;
    }
}

//获取客户端数据流
$str_xml_content = file_get_contents("php://input");
m_config::write_cdn_notify_log('片源媒体内容注入CDN反馈信息：' . addslashes($str_xml_content), ORG_ID, '');
//处理CDN上报内容
$obj_notify = new notify($str_xml_content);
$obj_notify->init();
//释放资源
unset($str_xml_content); unset($obj_notify);